package com.back.security;

import com.back.common.utils.JwtUtil;
import com.back.common.utils.RedisUtil;
import com.back.vo.JwtVo;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = (String) authentication.getCredentials();
        if (StringUtils.isNotBlank(token)) {
            if (JwtUtil.checkToken(token)) {
                Claims claims = JwtUtil.getTokenBody(token);
                JwtVo jwt = JwtVo.fromClaims(claims);
                String redisToken = redisUtil.get(String.valueOf(jwt.getId()));
                
                if (StringUtils.isNotEmpty(redisToken) && redisToken.equals(token)) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(jwt.getName());
                    return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                }
            }
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
} 